#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <memory>

// 演示为什么需要传递this指针

class ChatServer {
private:
    std::string serverName;
    std::vector<std::string> clients;
    int port;
    
public:
    ChatServer(const std::string& name, int p) : serverName(name), port(p) {}
    
    // 成员函数 - 需要访问对象的成员变量
    void handleClient(int clientId, const std::string& clientName) {
        std::cout << "🔧 处理客户端 " << clientId << " (" << clientName << ")" << std::endl;
        std::cout << "   服务器名: " << serverName << std::endl;  // 访问成员变量
        std::cout << "   服务器端口: " << port << std::endl;      // 访问成员变量
        
        // 调用其他成员函数
        addClient(clientName);
        showClients();
    }
    
    void addClient(const std::string& clientName) {
        clients.push_back(clientName);  // 访问成员变量
        std::cout << "   ✅ 客户端 " << clientName << " 已添加" << std::endl;
    }
    
    void showClients() {
        std::cout << "   👥 当前客户端数量: " << clients.size() << std::endl;
    }
    
    void demonstrateThreadCreation() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "  为什么需要传递 this 指针？" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        
        std::cout << "\n🎯 问题核心：成员函数需要对象实例才能调用" << std::endl;
        
        // 方式1：正确的方式 - 传递this指针
        std::cout << "\n✅ 正确方式：传递 this 指针" << std::endl;
        std::cout << "代码: std::thread(&ChatServer::handleClient, this, 1001, \"Alice\")" << std::endl;
        
        std::thread correctThread(&ChatServer::handleClient, this, 1001, "Alice");
        correctThread.join();
        
        // 方式2：错误的方式演示（编译不通过）
        std::cout << "\n❌ 错误方式：不传递 this 指针" << std::endl;
        std::cout << "代码: std::thread(&ChatServer::handleClient, 1002, \"Bob\")" << std::endl;
        std::cout << "结果: 编译错误！成员函数需要对象实例" << std::endl;
        
        // 这行代码会编译失败：
        // std::thread wrongThread(&ChatServer::handleClient, 1002, "Bob");
    }
};

// 对比：普通函数不需要this
void globalHandleClient(int clientId, const std::string& clientName) {
    std::cout << "🌐 全局函数处理客户端 " << clientId << " (" << clientName << ")" << std::endl;
    std::cout << "   无需访问对象成员，不需要this指针" << std::endl;
}

class ThreadExplanation {
public:
    static void explainMemberFunctionPointers() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "  成员函数指针详解" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        
        std::cout << "\n📚 理论基础：" << std::endl;
        std::cout << "1. 成员函数指针的类型：ReturnType (ClassName::*)(Parameters)" << std::endl;
        std::cout << "2. 成员函数调用需要：对象实例 + 函数指针 + 参数" << std::endl;
        std::cout << "3. std::thread 自动处理这个调用过程" << std::endl;
        
        std::cout << "\n🔍 具体分析：" << std::endl;
        std::cout << "void (ChatServer::*)(int, const std::string&) = &ChatServer::handleClient" << std::endl;
        std::cout << "这是一个指向ChatServer类成员函数的指针" << std::endl;
        
        std::cout << "\n⚙️ std::thread 的内部处理：" << std::endl;
        std::cout << "std::thread(&ChatServer::handleClient, this, 1001, \"Alice\")" << std::endl;
        std::cout << "等价于：this->handleClient(1001, \"Alice\")" << std::endl;
        
        std::cout << "\n🎯 参数映射：" << std::endl;
        std::cout << "  参数1: &ChatServer::handleClient  -> 成员函数指针" << std::endl;
        std::cout << "  参数2: this                      -> 对象实例指针" << std::endl;
        std::cout << "  参数3: 1001                      -> 函数的第1个参数" << std::endl;
        std::cout << "  参数4: \"Alice\"                   -> 函数的第2个参数" << std::endl;
    }
    
    static void explainMemoryLayout() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "  内存布局和this指针" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        
        ChatServer server1("Server-A", 8888);
        ChatServer server2("Server-B", 9999);
        
        std::cout << "\n🧠 内存布局：" << std::endl;
        std::cout << "server1 地址: " << &server1 << std::endl;
        std::cout << "server2 地址: " << &server2 << std::endl;
        
        std::cout << "\n📍 this 指针的作用：" << std::endl;
        std::cout << "1. 告诉成员函数操作哪个对象的数据" << std::endl;
        std::cout << "2. 区分不同对象实例的成员变量" << std::endl;
        std::cout << "3. 使成员函数能够访问正确的对象状态" << std::endl;
        
        std::cout << "\n🔬 实际效果演示：" << std::endl;
        std::cout << "两个不同的服务器对象，使用相同的成员函数：" << std::endl;
        
        std::thread t1(&ChatServer::handleClient, &server1, 1001, "Alice");
        std::thread t2(&ChatServer::handleClient, &server2, 1002, "Bob");
        
        t1.join();
        t2.join();
        
        std::cout << "\n✅ 结果：每个线程访问了正确的对象实例" << std::endl;
    }
};

class AlternativeApproaches {
public:
    static void demonstrateAlternatives() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "  其他传递方式" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        
        ChatServer server("Demo-Server", 7777);
        
        std::cout << "\n🎯 方式1：直接传递 this" << std::endl;
        std::cout << "std::thread(&ChatServer::handleClient, this, params...)" << std::endl;
        
        std::cout << "\n🎯 方式2：使用 std::ref" << std::endl;
        std::cout << "std::thread(&ChatServer::handleClient, std::ref(server), params...)" << std::endl;
        
        std::cout << "\n🎯 方式3：使用 lambda 表达式" << std::endl;
        std::cout << "std::thread([this](int id, const std::string& name) {" << std::endl;
        std::cout << "    this->handleClient(id, name);" << std::endl;
        std::cout << "}, params...)" << std::endl;
        
        std::cout << "\n🎯 方式4：使用 std::bind" << std::endl;
        std::cout << "std::thread(std::bind(&ChatServer::handleClient, this, " << std::endl;
        std::cout << "                      std::placeholders::_1, std::placeholders::_2)," << std::endl;
        std::cout << "            params...)" << std::endl;
        
        // 实际演示lambda方式
        std::cout << "\n🚀 Lambda方式演示：" << std::endl;
        std::thread lambdaThread([&server](int id, const std::string& name) {
            server.handleClient(id, name);
        }, 2001, "Charlie");
        
        lambdaThread.join();
    }
};

class CommonMistakes {
public:
    static void showCommonMistakes() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "  常见错误和解决方案" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        
        std::cout << "\n❌ 错误1：忘记传递this" << std::endl;
        std::cout << "// std::thread(&ChatServer::handleClient, 1001, \"Alice\");" << std::endl;
        std::cout << "编译错误：成员函数需要对象实例" << std::endl;
        
        std::cout << "\n❌ 错误2：传递错误的对象指针" << std::endl;
        std::cout << "ChatServer* wrongServer = nullptr;" << std::endl;
        std::cout << "// std::thread(&ChatServer::handleClient, wrongServer, 1001, \"Alice\");" << std::endl;
        std::cout << "运行时错误：空指针解引用" << std::endl;
        
        std::cout << "\n❌ 错误3：对象生命周期问题" << std::endl;
        std::cout << "void createThread() {" << std::endl;
        std::cout << "    ChatServer localServer(\"temp\", 8888);" << std::endl;
        std::cout << "    std::thread t(&ChatServer::handleClient, &localServer, 1001, \"Alice\");" << std::endl;
        std::cout << "    t.detach();  // 危险！localServer在函数结束时销毁" << std::endl;
        std::cout << "}" << std::endl;
        std::cout << "问题：线程可能访问已销毁的对象" << std::endl;
        
        std::cout << "\n✅ 解决方案：" << std::endl;
        std::cout << "1. 确保对象生命周期长于线程" << std::endl;
        std::cout << "2. 使用智能指针管理对象" << std::endl;
        std::cout << "3. 在对象析构时等待线程结束" << std::endl;
    }
};

int main() {
    std::cout << "🚀 std::thread 中的 this 指针详解" << std::endl;
    
    // 基本演示
    ChatServer server("Main-Server", 8888);
    server.demonstrateThreadCreation();
    
    // 理论解释
    ThreadExplanation::explainMemberFunctionPointers();
    
    // 内存布局
    ThreadExplanation::explainMemoryLayout();
    
    // 其他方式
    AlternativeApproaches::demonstrateAlternatives();
    
    // 常见错误
    CommonMistakes::showCommonMistakes();
    
    // 对比全局函数
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << "  对比：全局函数不需要this" << std::endl;
    std::cout << std::string(60, '=') << std::endl;
    
    std::cout << "\n🌐 全局函数线程创建：" << std::endl;
    std::cout << "std::thread(globalHandleClient, 3001, \"Global-Client\")" << std::endl;
    
    std::thread globalThread(globalHandleClient, 3001, "Global-Client");
    globalThread.join();
    
    std::cout << "\n📝 总结：" << std::endl;
    std::cout << "1. 成员函数需要对象实例才能调用" << std::endl;
    std::cout << "2. this 指针告诉函数操作哪个对象的数据" << std::endl;
    std::cout << "3. std::thread 会自动处理成员函数的调用" << std::endl;
    std::cout << "4. 不传递 this 会导致编译错误" << std::endl;
    std::cout << "5. 对象生命周期必须长于线程生命周期" << std::endl;
    
    return 0;
} 